package com.jdk.learn.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产消费者问题
 */
public class MultiThreadProductAndConsumer05 {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
        Product05 product = new Product05(queue);
        Product05 product2 = new Product05(queue);
        Consumer05 consumer = new Consumer05(queue);
        product.start();
        product2.start();
        consumer.start();
        Thread.sleep(10 * 1000);
        product.stopThread();
        product2.stopThread();
    }
}

class Product05 extends Thread {
    private BlockingQueue queue;
    private volatile boolean flag=true;
    private  static AtomicInteger count=new AtomicInteger();

    public Product05(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (flag) {
                String data=count.incrementAndGet()+"";
                boolean o = queue.offer(data);
                if (o) {
                    System.out.println(data + "添加成功");
                } else {
                    System.out.println(data+"添加失败");
                }
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("生产者结束");
        }
    }

    public void stopThread() {
        this.flag = false;
    }
}

class Consumer05 extends Thread {
    private BlockingQueue queue;
    private volatile boolean flag = true;
    public Consumer05(BlockingQueue queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        try {
            while (flag) {
                // 获取完毕，队列会删除掉
                String data = (String) queue.poll(2, TimeUnit.SECONDS);
                if (data != null) {
                    System.out.println("消费者获取 data:" + data + "成功...");
                } else {
                    System.out.println("消费者获取 data:" + data + "失敗..");
                    this.flag = false;
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("消费停止....");
        }
    }
}
